package com.champbay.blog.protobuf.web;

import com.champbay.blog.protobuf.model.AddressBookProtos;
import com.champbay.blog.protobuf.model.AddressBookProtos.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@Controller
public class TestController {
	
    @Autowired private RestTemplate restTemplate;

    @ResponseBody
    @RequestMapping(value = "/test",method = RequestMethod.POST, consumes = "application/x-protobuf", produces = "application/x-protobuf")
    public AddressBookProtos.Person getPersonProto(@RequestBody AddressBookProtos.Person person) {
        System.out.println("===========================进入接口=============================");
        System.out.println("id: " + person.getId());
        System.out.println("name: " + person.getName());
        System.out.println("email: " + person.getEmail());
        //这个地方需要加入将protobuf的对象转换成普通的java pojo的方法。
        Person.Builder builder = Person.newBuilder();
        builder.setId(2);
        builder.setName("myhello");
        builder.setEmail("myhello@aaa.com");
        return builder.build();
    }

    @ResponseBody
    @RequestMapping(value = "/test/rest/{id}",method = RequestMethod.GET)
    public String getPersonProtoToString(@PathVariable("id") Integer id){
        System.out.println("======================进入REST接口========================");
        Person.Builder person = Person.newBuilder();
        person.setId(1);
        person.setName("hello");
        person.setEmail("hello@aaa.com");
        byte[] personContent = person.build().toByteArray();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/x-protobuf");
        httpHeaders.set("Accept","application/x-protobuf");
        HttpEntity httpEntity = new HttpEntity(personContent,httpHeaders);
        ResponseEntity<String> restTemplateForEntity = restTemplate.postForEntity("http://127.0.0.1:8002/test",httpEntity,String.class);
        return restTemplateForEntity.getBody();
    }

}
